package com.yiya.ms.action;

import java.beans.PropertyEditorSupport;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.Bill;
import com.yiya.bean.SysUser;
import com.yiya.model.BillCplex;
import com.yiya.model.BillCplexModel;
import com.yiya.service.BillService;
import com.yiya.service.SysRoleService;
import com.yiya.utils.DataTypeUtil;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/bill")
public class BillAction extends BaseAction {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(BillAction.class);

	@Autowired
	private BillService billService;
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private SysRoleService sysRoleService;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }
		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        
		});
	}

	@RequestMapping("/product_in_list")
	public ModelAndView productInList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/in_bill", context);
	}
	
	@RequestMapping("/product_in_simple_list")
	public ModelAndView productInSimpleList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/in_bill_simple", context);
	}

	@RequestMapping("/product_out_list")
	public ModelAndView productOutList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/out_bill", context);
	}
	
	@RequestMapping("/product_out_simple_list")
	public ModelAndView productOutSimpleList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/out_bill_simple", context);
	}
	
	@RequestMapping("/material_in_list")
	public ModelAndView materialInList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/rm_in_bill", context);
	}

	@RequestMapping("/material_out_list")
	public ModelAndView materialOutList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/rm_out_bill", context);
	}
	

	@RequestMapping("/material_out_simple_list")
	public ModelAndView materialOutSimpleList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/rm_out_bill_simple", context);
	}
	
	@RequestMapping("/material_in_simple_list")
	public ModelAndView materialInSimpleList(Integer type, HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("bill/rm_in_bill_simple", context);
	}

	@RequestMapping("/dataList")
	public void datalist(BillCplexModel model, HttpServletRequest request,HttpServletResponse response)
			throws Exception {
		SysUser user = SessionUtils.getUser(request);
		int scope = sysRoleService.queryUserViewScope(user.getId());
		if(scope!=1){
			model.setCreateBy(user);
		}
		List<BillCplex> bills = billService.queryByList(model);
		int count = billService.queryByCount(model);
		
		Float priceSum = 0f;
		int quantitySum = 0;
		List<Map<String, Object>> footer = new ArrayList<Map<String, Object>>();
		Float price = 0f;
		int quantity = 0;
		for(BillCplex bill:bills){
			price = bill.getPrice()==null?0:bill.getPrice();
			quantity = bill.getQuantity()==null?0:bill.getQuantity();
			priceSum+=price*quantity;
			quantitySum+=quantity;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("number", "合计：");		
		map.put("quantity", quantitySum);
		map.put("price", DataTypeUtil.KeepDecimal(2, priceSum));
		footer.add(map);
		
		// 设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", bills);
		jsonMap.put("total", count);
		jsonMap.put("footer", footer);
		HtmlUtil.writerJson(response, jsonMap);
	}

	@RequestMapping("/save")
	public void save(Bill bean, HttpServletRequest request,
			HttpServletResponse response) {
		Date nowTime = new Date();
		SysUser user = SessionUtils.getUser(request);
		if(bean.getId()!=null){
			bean.setUpdateBy(user.getId());
			bean.setUpdateTime(nowTime);
			billService.Update(bean);
		}else{
			bean.setCreateTime(nowTime);
			bean.setCreateBy(user.getId());
			billService.add(bean);
		}
		sendSuccessMessage(response, "保存成功");
	}

	@RequestMapping("/getId")
	public void getId(Integer id, HttpServletResponse response) {
		Map<String, Object> context = getRootMap();
		Bill bill = billService.queryById(id);
		if (bill == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bill);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		billService.delete(id,user);
		sendSuccessMessage(response, "删除成功");
	}
	
	@RequestMapping("/check")
	public void check(Integer[] id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		int result = billService.check(id,user);
		if(result!=0){
			sendSuccessMessage(response, "确认成功");
		}else{
			sendFailureMessage(response, "部分产品库存不足，库存不足的产品无法出库!");
		}
		
	}
	
	/**
	 * 导出
	 * @param model
	 * @param type {1:含价格,2:不含价格}
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/export_out_bill/{pType}")
	public void exportOutBill(BillCplexModel model, @PathVariable String pType, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SysUser user = SessionUtils.getUser(request);
		int scope = sysRoleService.queryUserViewScope(user.getId());
		if(scope!=1){
			model.setCreateBy(user);
		}
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		List<BillCplex> bills = billService.queryAllByList(model);
		int typeInt = pType==null?2:Integer.valueOf(pType);
		HSSFWorkbook wb = billService.export(bills,typeInt);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="+format.format(date)+".xls"); 
		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);    
        ouputStream.flush();    
        ouputStream.close(); 
	}

}
